<script setup lang="ts">
import { ref,onMounted,onUpdated } from 'vue'
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
import { QuillBinding } from 'y-quill'
import Quill from 'quill'
import QuillCursors from 'quill-cursors'
import DoUsername from 'do_username'
import '../../../node_modules/quill/dist/quill.snow.css'
// import '../../../node_modules/quill/dist/quill.bubble.css'

let isShow = ref(false);

let isInit=false;

let showView=()=>{
    if(isInit){
        return;
    }
    isInit=true;

    Quill.register('modules/cursors', QuillCursors)

    const quill = new Quill(document.querySelector('#editor6'), {
    modules: {
        cursors: true,
        toolbar: [
        // adding some basic Quill content features
        [{ header: [1, 2, false] }],
        ['bold', 'italic', 'underline'],
        ['image', 'code-block']
        ],
        history: {
        // Local undo shouldn't undo changes
        // from remote users
        userOnly: true
        }
    },
    placeholder: 'Start collaborating...',
    theme: 'snow' // snow,'bubble' is also great
    })

    // A Yjs document holds the shared data
    const ydoc = new Y.Doc()

    // connect to the public demo server (not in production!)
    const provider = new WebsocketProvider(
        'ws://localhost:1234', 'quill-editor-room-1', ydoc
    )

    provider.on('status', event => {
        console.log(`ws status:${event.status}`) // logs "connected" or "disconnected"
    })

    // All network providers implement the awareness protocol. You can use it to propagate information about yourself.
    const awareness = provider.awareness;
    
    // Define a shared text type on the document
    const ytext = ydoc.getText('quill')

    // "Bind" the quill editor to a Yjs text type.
    const binding = new QuillBinding(ytext, quill, awareness)

    // Remove the selection when the iframe is blurred
    // window.addEventListener('blur', () => { quill.blur() })

    // Each user should be associated to a color.
    // One approach is to pick a random color from a pool of colors that work well with your project.
    const usercolors = [
    '#30bced',
    '#6eeb83',
    '#ffbc42',
    '#ecd444',
    '#ee6352',
    '#9ac2c9',
    '#8acb88',
    '#1be7ff'
    ]

    const myColor = usercolors[Math.floor(Math.random() * usercolors.length)]

    const inputElement: HTMLInputElement = document.querySelector('#username')
    // propagate the username from the input element to all users
    const setUsername = () => {
        awareness.setLocalStateField('user', { name: inputElement.value, color: myColor })
    }

    // observe changes on the input element that contains the username
    inputElement.addEventListener('input', setUsername)

    // Render a list of usernames next to the editor whenever new information is available from the awareness instance
    awareness.on('change', () => {
        // Map each awareness state to a dom-string
        const strings = []
        awareness.getStates().forEach(state => {
            console.log(state)
            if (state.user) {
                strings.push(`<div style="color:${state.user.color};">• ${state.user.name}</div>`)
            }
            document.querySelector('#users').innerHTML = strings.join('')
        })
    })

    // Set a randomly generated username - this is nice for testing
    inputElement.value = DoUsername.generate(15)
    setUsername()

}

onMounted(()=>{
    
})

onUpdated(()=>{
    if(isShow.value==true){
        showView();
    }
})

</script>

<template>
    <div class="hide"><input type="button" :value="`${isShow ? 'hide' : 'show'} yjs 6`" @click="isShow = !isShow"></div>
    <div v-show ="isShow">
        <div class="desc">Y JS 示例 ：Quill 编辑器集成 + Y-WebSocket + 感知服务,需要执行 yarn run websocket</div>
        <br>
        <label for="username">Your username</label>
        <input id="username" type="text" />
        <div id="users" class="users"></div>

        <div id="editor6" class="editor"></div>
    </div>
</template>

<style scoped>
/* @import './styles/katex.min.css'; */
/* @import './styles/monokai-sublime.min.css'; */
.users {
    font-weight: bold;
    margin: 1em 1em;
}
  
.editor{
    width:600px;
    height:400px;
}
</style>